package com.aiti.myproject.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.aiti.myproject.shared.UploadImage;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.gwt.user.client.Window;

public class UploadedImageDAO {
	private DatastoreService datastoreService;

	public UploadedImageDAO() {
		datastoreService = DatastoreServiceFactory.getDatastoreService();
	}

	public UploadImage get(String encodeKey) {
		Key key = KeyFactory.stringToKey(encodeKey);
		Window.alert("here");
		try {
			Entity entity = datastoreService.get(key);
			UploadImage uploadImage = fromEntity(entity);
			uploadImage.setKey(encodeKey);
			return uploadImage;
		} catch (EntityNotFoundException e) {
			Window.alert(e.getMessage());
			return null;
		}
	}

	public List<UploadImage> getRecent() {
		Query query = new Query("UploadImage");
		query.addSort(UploadImage.CREATE_AT, SortDirection.DESCENDING);
		FetchOptions fetchOptions = FetchOptions.Builder.withLimit(25);
		ArrayList<UploadImage> images = new ArrayList<UploadImage>();
		for (Entity entity : datastoreService.prepare(query).asIterable(
				fetchOptions)) {
			UploadImage image = fromEntity(entity);
			images.add(image);
		}
		return images;
	}

	public void delete(String encodeKey) {
		Key key = KeyFactory.stringToKey(encodeKey);
		datastoreService.delete(key);
	}

	private UploadImage fromEntity(Entity entity) {
		UploadImage image = new UploadImage();
		image.setCreateAt((Date) entity.getProperty(UploadImage.CREATE_AT));
		image.setServingUrl((String) entity
				.getProperty(UploadImage.SERVING_URL));
		image.setOwnerId((String) entity.getProperty(UploadImage.OWNER_ID));
		if (null == image.getKey()) {
			String encodeKey = KeyFactory.keyToString(entity.getKey());
			image.setKey(encodeKey);
		}
		return image;
	}
}
